package com.seeyon.apps.brwh.kit;

import com.seeyon.apps.brwh.service.FormTableWordService;
import com.seeyon.ctp.common.log.CtpLogFactory;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteException;
import org.apache.commons.exec.ExecuteResultHandler;
import org.apache.commons.logging.Log;

import java.io.File;
import java.util.concurrent.Semaphore;

/**
 * word转pdf
 * 需要安装 LibreOffice 插件
 * 借鉴网址：https://www.jianshu.com/p/8fc4f29f3e3a
 */
public class WordChangePdfKit {
    private static final Log log = CtpLogFactory.getLog(FormTableWordService.class);

    /**
     * 转换
     * @param tempFolder   临时存放目录
     * @param outputFile   需要转换的文件
     * @return   返回转换后的文件File
     */
    public static File convert(File tempFolder, File outputFile) {
        File file = null;
        try {
            DefaultExecutor exec = new DefaultExecutor();
            // 同步等待
            Semaphore semaphore = new Semaphore(1);
            semaphore.acquire();
            ExecuteResultHandler erh = new ExecuteResultHandler() {
                @Override
                public void onProcessComplete(int i) {
                    semaphore.release();
                    //转换完成逻辑
                    log.info("word转换PDF成功--------");
                }

                @Override
                public void onProcessFailed(ExecuteException e) {
                    semaphore.release();
                    //转换失败逻辑
                    log.info("word转换PDF异常--------");
                }
            };
            String command = "soffice --invisible --convert-to pdf --outdir \"" + tempFolder.getAbsolutePath() + "\" \"" + outputFile.getAbsolutePath() + "\"";
            log.info("执行office文件转换任务，命令为：" + command);
            exec.execute(CommandLine.parse(command), erh);
            // 等待执行完成
            semaphore.acquire();
            file = new File(tempFolder.getAbsolutePath() + File.separator + outputFile.getName().substring(0, outputFile.getName().indexOf(".")) + ".pdf");
            if (!file.exists()) {
                log.info("word转pdf错误，检查是否安装LibreOffice。安装教程借鉴已下网址：https://www.jianshu.com/p/8fc4f29f3e3a");
            }
        }catch (Exception e) {
            log.info("word转pdf异常：",e);
        }
        return file;
    }
}
